# 序列化-json
# json是一种数据交换格式

import json

vard = {'name': '张三', 'age': 18, 'hobble': 'sleep'}
res = json.dumps(vard)
# print(res, type(res))
# {"name": "\u5f20\u4e09", "age": 18, "hobble": "sleep"} <class 'str'>
res = json.loads(res)
# print(res, type(res))
# {'name': '张三', 'age': 18, 'hobble': 'sleep'} <class 'dict'>

# 其他数据类型也能进行转换
vars = '123'
varl = [1, 2, 3]
varn = 123
varf = 123.1
# print(json.dumps(vars))
# "123"
# print(json.loads(json.dumps(vars)))
# 123

# 将写入文件 / 从文件中读取数据
varl = [
    {'name': '张三', 'age': 18, 'hobble': 'sleep'},
    {'name': '张三', 'age': 18, 'hobble': 'sleep'}
]
# 写入
with open('./data.json', 'w') as fp:
    json.dump(varl, fp)
# 读取
with open('./data.json', 'r') as fp:
    res = json.load(fp)
#     [{'name': '张三', 'age': 18, 'hobble': 'sleep'}, {'name': '张三', 'age': 18, 'hobble': 'sleep'}]

print(res)
